import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { authAPI } from '../../services/api';

// 安全处理localStorage
const safeStorage = {
  setItem: (key, value) => {
    try {
      localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
    } catch (e) {
      console.error('localStorage setItem error:', e);
    }
  },
  getItem: (key, parse = false) => {
    try {
      const value = localStorage.getItem(key);
      return parse && value ? JSON.parse(value) : value;
    } catch (e) {
      console.error('localStorage getItem error:', e);
      return null;
    }
  },
  removeItem: (key) => {
    try {
      localStorage.removeItem(key);
    } catch (e) {
      console.error('localStorage removeItem error:', e);
    }
  }
};

// 清除认证数据
const clearAuthData = () => {
  safeStorage.removeItem('token');
  safeStorage.removeItem('user');
};

// 保存认证数据
const saveAuthData = (token, user) => {
  if (token) {
    safeStorage.setItem('token', token);
  }
  
  if (user) {
    safeStorage.setItem('user', user);
  }
};

// 异步登录
export const loginStudent = createAsyncThunk(
  'auth/loginStudent',
  async ({ studentId, password }, { rejectWithValue }) => {
    try {
      const response = await authAPI.login({ student_id: studentId, password });
      
      // 统一处理各种响应格式
      if (response.data) {
        let token = null;
        let student = null;
        
        // 提取token和用户信息，处理不同格式的响应
        if (response.data.code === 2000 || response.data.code === 200 || response.data.code === 0) {
          // 从响应中获取数据，适应不同格式
          token = response.data.token || response.data.data?.token;
          student = response.data.student || response.data.data?.student;
          
          if (student?.student_id || student?.id) {
            // 确保存储到localStorage
            saveAuthData(token, student);
            return { token, student };
          }
        }
      }
      
      return rejectWithValue(response.data?.message || '登录失败');
    } catch (error) {
      console.error('Login error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '登录失败，请检查网络连接');
    }
  }
);

// 异步注册
export const registerStudent = createAsyncThunk(
  'auth/registerStudent',
  async ({ studentId, name, password, classId }, { rejectWithValue }) => {
    try {
      const response = await authAPI.register({ 
        student_id: studentId, 
        name, 
        password,
        class_id: classId
      });
      if (response.data.code === 200 || response.data.code === 0 || response.data.code === 2000) {
        return response.data;
      }
      return rejectWithValue(response.data.message || '注册失败');
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '注册失败，请检查网络连接');
    }
  }
);

// 使用token获取用户信息
export const getUserInfo = createAsyncThunk(
  'auth/getUserInfo',
  async (_, { getState, rejectWithValue, signal }) => {
    try {
      const { token, loading, user } = getState().auth;
      
      // 如果已经在加载中，则不重复请求
      if (loading) {
        console.log('已有请求在进行中，跳过此次请求');
        return rejectWithValue('请求已在进行中');
      }
      
      // 如果已经有用户信息，且不是强制刷新，则直接返回现有用户信息
      if (user && _.forceRefresh !== true) {
        console.log('已有用户信息，跳过请求');
        return user;
      }
      
      if (!token) {
        return rejectWithValue('未登录');
      }
      
      // 添加请求标识，允许中断请求
      const controller = new AbortController();
      signal.addEventListener('abort', () => {
        controller.abort();
      });
      
      // 添加超时处理
      const timeoutId = setTimeout(() => {
        controller.abort();
      }, 5000); // 5秒超时
      
      try {
        console.log('开始获取用户信息');
        // 使用唯一标识符防止缓存
        const timestamp = new Date().getTime();
        const response = await authAPI.getUserInfo({ 
          params: { _t: timestamp },
          signal: controller.signal
        });
        
        // 清除超时
        clearTimeout(timeoutId);
        
        if (response.data && (response.data.code === 2000 || response.data.code === 200 || response.data.code === 0)) {
          // 保存用户信息到本地存储
          saveAuthData(null, response.data.data);
          console.log('用户信息获取成功');
          return response.data.data;
        }
        return rejectWithValue(response.data?.message || '获取用户信息失败');
      } catch (error) {
        // 清除超时
        clearTimeout(timeoutId);
        throw error;
      }
    } catch (error) {
      // 处理请求被取消的情况
      if (error.name === 'AbortError' || error.code === 'ECONNABORTED') {
        return rejectWithValue('请求被取消或超时');
      }
      
      // 如果是401错误，清除token
      if (error.response?.status === 401) {
        clearAuthData();
      }
      return rejectWithValue(error.response?.data?.message || '获取用户信息失败');
    }
  },
  {
    // 添加条件，避免频繁调用
    condition: (_, { getState }) => {
      const { loading, user } = getState().auth;
      // 如果已经有请求正在进行或已有用户信息，则不发起新请求
      if (loading || (user && _.forceRefresh !== true)) {
        return false;
      }
      return true;
    }
  }
);

// 退出登录
export const logoutStudent = createAsyncThunk(
  'auth/logoutStudent',
  async (_, { rejectWithValue }) => {
    try {
      const response = await authAPI.logout();
      if (response.data.code === 200 || response.data.code === 0) {
        clearAuthData();
        return response.data;
      }
      return rejectWithValue(response.data.message || '退出失败');
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '退出失败');
    } finally {
      // 无论成功失败都清除本地存储
      clearAuthData();
    }
  }
);

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    user: safeStorage.getItem('user', true),
    token: safeStorage.getItem('token'),
    isAuthenticated: !!safeStorage.getItem('token'),
    loading: false,
    error: null,
  },
  reducers: {
    logout: (state) => {
      state.user = null;
      state.token = null;
      state.isAuthenticated = false;
      clearAuthData();
    },
    clearError: (state) => {
      state.error = null;
    },
    // 检查本地存储中的token
    checkAuthState: (state) => {
      const token = safeStorage.getItem('token');
      const user = safeStorage.getItem('user', true);
      
      if (token) {
        state.token = token;
        state.isAuthenticated = true;
        state.user = user;
      } else {
        state.token = null;
        state.user = null;
        state.isAuthenticated = false;
      }
    }
  },
  extraReducers: (builder) => {
    builder
      // 登录
      .addCase(loginStudent.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(loginStudent.fulfilled, (state, action) => {
        state.loading = false;
        
        if (action.payload) {
          const { token, student } = action.payload;
          
          if (token) {
            state.token = token;
            state.isAuthenticated = true;
          }
          
          if (student) {
            state.user = student;
          }
        }
      })
      .addCase(loginStudent.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '登录失败';
        state.isAuthenticated = false;
        state.token = null;
        state.user = null;
        clearAuthData();
      })
      
      // 注册
      .addCase(registerStudent.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(registerStudent.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(registerStudent.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '注册失败';
      })
      
      // 获取用户信息
      .addCase(getUserInfo.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getUserInfo.fulfilled, (state, action) => {
        state.loading = false;
        state.user = action.payload;
        state.isAuthenticated = true;
      })
      .addCase(getUserInfo.rejected, (state, action) => {
        state.loading = false;
        if (action.payload === '未登录' || action.error?.message?.includes('401')) {
          state.isAuthenticated = false;
          state.token = null;
          state.user = null;
          clearAuthData();
        } else {
          state.error = action.payload || '获取用户信息失败';
        }
      })
      
      // 退出登录
      .addCase(logoutStudent.pending, (state) => {
        state.loading = true;
      })
      .addCase(logoutStudent.fulfilled, (state) => {
        state.loading = false;
        state.user = null;
        state.token = null;
        state.isAuthenticated = false;
      })
      .addCase(logoutStudent.rejected, (state) => {
        state.loading = false;
        state.user = null;
        state.token = null;
        state.isAuthenticated = false;
      });
  },
});

export const { logout, clearError, checkAuthState } = authSlice.actions;
export default authSlice.reducer;